package db

import (
	"gopkg.in/mgo.v2"
	"fmt"
	log "github.com/sirupsen/logrus"
)

type Mongodb struct {
	Session  *mgo.Session
	Server   string
	DbName   string
	Host     string
	Port     int
}


func NewMongodb(host string, port int, dbname string, args ...interface{}) *Mongodb{

	model  := new(Mongodb)

	var err error

	model.DbName       = dbname

	model.Host         = host

	model.Port         = port

	model.Server       = fmt.Sprintf("%s:%d", host, port)

	model.Session, err = mgo.Dial(model.Server)
	
	log.Infof("[mongodb: %s]: %s", model.DbName, model.Server)

	if err != nil {
		log.Errorln("[mongodb: %s]: error: %v", model.DbName, err.Error())
		panic(err)
	}else{
		log.Infof("[mongodb: %s]: success", model.DbName)
	}
	
	model.Session.SetMode(mgo.Monotonic, true)

	return model
}

func (this *Mongodb) S() *mgo.Session {
    if this.Session == nil {
        var err error
        this.Session, err = mgo.Dial(this.Server)
        if err != nil {
            panic(err) // no, not really
        }
    }
    return this.Session.Clone()
}

func (this *Mongodb) M(collection string, f func(*mgo.Collection)) {
	session := this.S()
    defer func() {
        session.Close()
        if err := recover(); err != nil {
            log.Errorf("[%s:%s]M recover error: ", this.Server, this.DbName, err)
        }
    }()
	c := session.DB(this.DbName).C(collection)
	f(c)
}